<template>
  <div class="app-container">
    <div class="top" style="margin-top: 28px;">
      <el-input
        v-model="kwInput"
        style="width: 40%"
        placeholder="输入 网站编码 或 域名 进行筛选"
        class="input-with-select"
        clearable
        @keyup.native.enter="handleSearch"
      >
        <el-button slot="append" icon="el-icon-search" :disabled="listLoading" @click="handleSearch">搜索</el-button>
      </el-input>
      <el-button type="warning" @click="taskVisible=true">查看任务队列</el-button>
      <el-button type="success" @click="handleAction('create', '')">添加新网站</el-button>
    </div>

    <el-table v-loading.body="listLoading" :data="data" border fit highlight-current-row style="width: 100%">

      <el-table-column align="center" label="域名">
        <template slot-scope="scope">
          <el-input v-show="scope.row.edit" v-model="scope.row.domain" class="edit-input" size="small" />
          <span v-show="!scope.row.edit">{{ scope.row.domain }}</span>
        </template>
      </el-table-column>

      <el-table-column label="项目属性" align="center" width="180">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.project_id"
            size="mini"
            placeholder="无"
            @change="handleProjectChange(scope.row)"
          >
            <el-option
              v-for="item in projects"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="550">
        <template slot-scope="scope">
          <el-button
            size="mini"
            icon="el-icon-refresh"
            type="success"
            plain
            @click="sync('catalog', scope.row.id, 0)"
          >抓取目录
          </el-button>
          <el-button
            size="mini"
            icon="el-icon-refresh"
            type="success"
            plain
            @click="sync('product', scope.row.id, 0)"
          >未抓取的产品
          </el-button>
          <el-button
            size="mini"
            icon="el-icon-refresh"
            type="danger"
            plain
            @click="sync('product', scope.row.id, 1)"
          >重爬所有
          </el-button>
          <el-button size="mini" type="warning" plain @click="handleAction('edit', scope.row)">修改</el-button>
          <el-button
            size="mini"
            icon="el-icon-refresh"
            type="danger"
            plain
            @click="handle_delete( scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>

    </el-table>

    <el-pagination
      v-if="data.length"
      background
      class="mt-pagination"
      :current-page="page"
      :page-sizes="[10,20,50,100]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
    />
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form v-if="action !== 'delete'" ref="dataForm" :model="temp" label-position="left" label-width="40px">
        <el-form-item label="项目">
          <el-select v-model="temp.project_id" v-loading="projectsLoading" placeholder="选择项目" filterable clearable>
            <el-option
              v-for="(item,index) in projects"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="域名">
          <el-input v-model="temp.domain" />
        </el-form-item>
        <el-form-item label="type">
          <el-input v-model="temp.type" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
    <crawltask :task-visible="taskVisible" @closeCrawlTaskDialog="taskVisible=false" />
  </div>
</template>

<script>
import { GetWebs, ModifyWeb, Sync, Delete, Post, Put } from '@/api/erp/crawlproduct'
import { Get as GetProjects } from '@/api/erp/elicink/project'
import crawltask from '@/views/crawl/elements/crawltask'
import qs from 'qs'

export default {
  name: 'SiteManage',
  components: { crawltask },
  data() {
    return {
      taskVisible: false,
      data: [],
      listLoading: true,
      // 输入
      kwInput: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,

      action: null,
      dialogVisible: false,
      dialogInputValue: '',
      dialogInputVsible: false,
      title: '',
      temp: {
        domain: '',
        type: 'PrestaShop'
      },
      projects: []
    }
  },
  created() {
    GetProjects()
      .then(response => {
        this.projects = response.data.data
      })
    this.getList()
  },
  methods: {
    resetTemp() {
      this.temp = {
        domain: '',
        type: 'PrestaShop'
      }
    },
    handleAction(action, row) {
      this.action = action
      this.dialogVisible = true
      switch (action) {
        case 'create':
          this.title = '添加新网站'
          this.resetTemp()
          break
        case 'edit':
          this.title = `修改${row.domain}`
          this.temp = Object.assign({}, row)
          break
      }
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        case 'create':
          Post(this.temp).then(response => {
            this.dialogVisible = false
            this.getList()
            this.notify('添加成功')
          }).catch(err => {
            console.log(err)
            this.dialogVisible = false
          })
          break
        case 'edit':
          Put(_data.id, { domain: _data.domain, type: _data.type }).then((response) => {
            this.dialogVisible = false
            this.getList()
            this.notify('更新成功')
          }).catch(err => {
            console.log(err)
            this.dialogVisible = false
          })
          break
      }
    },
    handle_delete(row) {
      this.$confirm('确定删除爬虫目标网站+' + row.domain + '?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        Delete(row.id).then(response => {
          this.notify('删除成功')
          this.getList()
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    sync(mode, id, force) {
      this.listLoading = true
      Sync(mode, id, force).then(response => {
        this.listLoading = false
        const data = response.data
        this.notify('任务发布成功.' + data.msg)
      }).catch(err => {
        console.log(err)
        this.listLoading = false
      })
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    getList() {
      this.listLoading = true
      GetWebs(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        page: this.page
      }))
        .then(response => {
          const items = response.data
          this.data = items
          this.listLoading = false
          this.total = response.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleProjectChange(v) {
      this.listLoading = true
      console.log(v.project_id)
      ModifyWeb(JSON.stringify({
        pk: v.id,
        project_id: v.project_id
      })
      ).then(response => {
        this.listLoading = false
        // this.getList()
      }).catch(e => {
        this.listLoading = false
      })
    } // method end
  }
}
</script>

<style scoped>

  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }

  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

  .input-with-select {
    width: calc(100% - 200px);
  }

  .add-btn {
    float: right;
    margin-right: 20px;
    width: 130px
  }

  .top {
    padding-left: 20px;
    margin-bottom: 30px;
  }

  .mt-pagination {
    float: right;
    margin-top: 5px;
  }

  .app-container >>> span.el-tag--info {
    word-break: normal;
    width: auto;
    display: block;
    white-space: pre-wrap;
    word-wrap: break-word;
    overflow: hidden;
  }
</style>
